import os
import json
import shutil
import time

import util
import sys


def Get_All_Items():
    items = [
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPrefix.git",
            "item_name": "MOPrefix"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPublic.git",
            "item_name": "MOPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOIM.git",
            "item_name": "MOIM"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOIMPublic.git",
            "item_name": "MOIMPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOLogin.git",
            "item_name": "MOLogin"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOLoginPublic.git",
            "item_name": "MOLoginPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOMoment.git",
            "item_name": "MOMoment"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOMomentPublic.git",
            "item_name": "MOMomentPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOAlbumModule.git",
            "item_name": "MOAlbumModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOAlbumPublic.git",
            "item_name": "MOAlbumPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPocket.git",
            "item_name": "MOPocket"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPocketPublic.git",
            "item_name": "MOPocketPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOExplorePublic.git",
            "item_name": "MOExplorePublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOExplore.git",
            "item_name": "MOExplore"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOShareModule.git",
            "item_name": "MOShareModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOSharePublic.git",
            "item_name": "MOSharePublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOAnalyticsModule.git",
            "item_name": "MOAnalyticsModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOMineModule.git",
            "item_name": "MOMineModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOMinePublic.git",
            "item_name": "MOMinePublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOCollectModule.git",
            "item_name": "MOCollectModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOCollectPublic.git",
            "item_name": "MOCollectPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOSettingModule.git",
            "item_name": "MOSettingModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOSettingPublic.git",
            "item_name": "MOSettingPublic"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPersonalInfomationModule.git",
            "item_name": "MOPersonalInfomationModule"
        },
        {
            "remote_url": "git@182.92.161.213:ios/project/mostone/MOPersonalInfomationPublic.git",
            "item_name": "MOPersonalInfomationPublic"
        }
    ]

    return items


def xcode_build(proj_path, proj_name, target_name=None, schema_name=None, configuration="Debug", **keywords):
    """
    xcode执行编译
    :param proj_path:
    :param proj_name:
    :param target_name:
    :param schema_name:
    :param configuration:
    :param keywords:
    :return:
    """
    #工程名
    if not os.path.exists(proj_path):
        return

    #pod install
    util.excute_shell("pod install --verbose", path=proj_path, pipe_out=False)

    command = "xcodebuild build"
    if ".xcworkspace" in proj_name:
        command = command + " -workspace " + proj_name
        proj_name = proj_name.split(".xcworkspace")[0]
    elif ".xcodeproj" in proj_name:
        command = command + " -project " + proj_name
        proj_name = proj_name.split(".xcodeproj")[0]

    if target_name is None:
        target_name = proj_name
    # #target
    # command = command + " -target " + target_name
    if schema_name is None:
        schema_name = target_name
    #schema
    command = command + " -scheme " + schema_name
    #
    command = command + " -configuration " + configuration
    #print(command)

    return util.excute_shell(command, path=proj_path, pipe_out=False)


def xcode_speed_package(env_config_path, ipa_save_path=None):
    """
    xcode快速取包
    :return:
    """
    print("取包啦...")
    if env_config_path is None:
        print("python日志 xcode编译环境参数文件不存在")
        return
    with open(env_config_path, "r") as f:
        env_config_data = json.load(f)
        build_dir_path = env_config_data["BUILD_DIR"]
    app_name = env_config_data["PRODUCT_NAME"]
    app_ext = ".app"
    app_path = os.path.join(build_dir_path, "Build/Products/Debug-iphoneos", app_name+app_ext)
    env_dir = os.path.dirname(env_config_path)
    temp_path = env_dir + "/temp"
    payload_path = temp_path + "/Payload"
    payload_app_path = payload_path + "/" + app_name+app_ext
    if os.path.exists(temp_path):
        shutil.rmtree(temp_path)
        time.sleep(1)
    os.makedirs(temp_path)
    shutil.copytree(app_path, payload_app_path)
    zip_path = shutil.make_archive(payload_path, "zip", temp_path)
    if ipa_save_path is None:
        ipa_save_path = temp_path+"/"+app_name+".ipa"
    iap_path = shutil.move(zip_path, ipa_save_path)
    if os.path.exists(payload_path):
        shutil.rmtree(payload_path)
    if os.path.exists(zip_path):
        shutil.rmtree(zip_path)
    print("取包啦...")
    return iap_path


def xcode_get_build_env(save_path=None):
    """
    读取xcode编译时的环境参数
    :param save_path:
    :return:
    """
    if save_path is None:
        save_path = os.getcwd() + "/build_env_config.json"
    needConfig = {}
    product_name = os.getenv("PRODUCT_NAME")
    build_dir_path = os.getenv("BUILD_DIR")
    if build_dir_path is None: return
    build_str_index = build_dir_path.find("Build/")
    if build_str_index is not None:
        build_dir_path = build_dir_path[0:build_str_index]
        needConfig["BUILD_DIR"] = build_dir_path
    needConfig["PRODUCT_NAME"] = product_name
    with open(save_path, "w") as f:
        json.dump(needConfig, f)


def sync_code(git_path, branch="dev"):
    for item in Get_All_Items():
        item_path = git_path + "/" + item["item_name"]
        if os.path.exists(item_path):
            # got pull
            print("exist item: ", item["item_name"])
            util.git_pull(git_path=item_path)
        else:
            # git clone
            print("not exist item: ", item["item_name"])
            util.git_clone(git_path=git_path, branch=branch, remote_url=item["remote_url"], item_name=item["item_name"])


if __name__ == "__main__":
    """
    命令行格式
    第一个参数 函数名
    其余按顺序存入函数需要的参数
    """
    args = sys.argv[1:]
    if len(args) == 0:
        sys.exit("参数缺失")
    method = args[0]
    args = args[1:]
    print("python日志 xcode.py文件执行命令行 method:{}, args:{}".format(method, args))

    if method == "xcode_get_build_env":
        xcode_get_build_env(args[0] if len(args) > 0 else None)
    elif method == "xcode_build":
        if len(args) > 1:
            proj_path = args[0]
            proj_name = args[1]
            xcode_build(proj_path, proj_name)
    elif method == "xcode_speed_package":
        ipa_save_path = None
        if len(args) > 1:
            ipa_save_path = args[1]
        xcode_speed_package(args[0] if len(args) > 0 else None, ipa_save_path)
    elif method == "sync_code":
        git_path = args[0]
        sync_code(git_path)